﻿@page "/Account/Login"
@using Microsoft.EntityFrameworkCore
@using WebFile.BlazorServer.Providers
@using WebFile.Share.Data
@inject IDbContextFactory<WebFileContext> DbFactory
@inject NavigationManager navigation
@inject AuthenticationStateProvider AuthStateProvider
@inject MessageService MessageService

<Row ItemsPerRow="ItemsPerRow.One">
    <Card IsShadow="true" IsCenter="true">
        <BodyTemplate>
            <h2>登录</h2>
            <ValidateForm OnValidSubmit="@Done" Model="@Model">
                <Row ItemsPerRow="ItemsPerRow.One">
                    <FloatingLabel PlaceHolder="Name" DisplayText="账号" IsGroupBox="true" @bind-Value="@Model.UserName" TValue="string"/>
                    <FloatingLabel PlaceHolder="Password" DisplayText="密码" IsGroupBox="true" TValue="string" @bind-Value="@Model.Password" type="password"/>
                    <Button style="width: 100%"
                            IsAsync="true" ButtonType="ButtonType.Submit"
                            Color="Color.Primary" Icon="oi oi-account-login" Text="登录">
                    </Button>
                    <Divider/>
                    <p>没有账号？去<NavLink href="/Account/Signup" Match="NavLinkMatch.All">注册</NavLink>一个</p>
                </Row>
            </ValidateForm>
        </BodyTemplate>
    </Card>
</Row>

@code {

    public UserModel Model { get; set; } = new();

    private async Task Done(EditContext arg)
    {
        if (string.IsNullOrEmpty(Model.UserName) || string.IsNullOrEmpty(Model.Password))
        {
            await MessageService.Show(new MessageOption() { Content = "没数据" });
            return;
        }

        await using var context = await DbFactory.CreateDbContextAsync();

        if (!await context.Users.AnyAsync(x => x.Password == Model.Password && x.UserName == Model.UserName))
        {
            await MessageService.Show(new MessageOption() { Content = "账号密码出错" });
            return;
        }
        var provider = (Provider)AuthStateProvider;
        await provider.UpdateAuthState(Model);
        navigation.NavigateTo("", true);
    }

}